package com.example.zhinongbao.model;

import android.content.ContentValues;
import android.database.Cursor;

import com.example.zhinongbao.provider.ZhinongbaoContract.Messages;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Message {
    private long id;
    private final String content;
    private final Date timestamp;
    private final boolean isSent; // true: 自己发送, false: 接收

    public Message(long id, String content, Date timestamp, boolean isSent) {
        this.id = id;
        this.content = content;
        this.timestamp = timestamp;
        this.isSent = isSent;
    }

    public Message(String content, boolean isSent) {
        this(-1, content, new Date(), isSent);
    }

    // 从Cursor构建Message对象
    public static Message fromCursor(Cursor cursor) {
        long id = cursor.getLong(cursor.getColumnIndexOrThrow(Messages._ID));
        String content = cursor.getString(cursor.getColumnIndexOrThrow(Messages.COLUMN_CONTENT));
        long timestampMillis = cursor.getLong(cursor.getColumnIndexOrThrow(Messages.COLUMN_TIMESTAMP));
        int isSentValue = cursor.getInt(cursor.getColumnIndexOrThrow(Messages.COLUMN_IS_SENT));

        return new Message(
                id,
                content,
                new Date(timestampMillis),
                isSentValue == 1
        );
    }

    // 转换为ContentValues用于数据库操作
    public ContentValues toContentValues() {
        ContentValues values = new ContentValues();
        values.put(Messages.COLUMN_CONTENT, content);
        values.put(Messages.COLUMN_TIMESTAMP, timestamp.getTime());
        values.put(Messages.COLUMN_IS_SENT, isSent ? 1 : 0);
        return values;
    }

    public String getFormattedTime() {
        return new SimpleDateFormat("HH:mm", Locale.getDefault()).format(timestamp);
    }

    // Getter方法
    public long getId() { return id; }
    public String getContent() { return content; }
    public Date getTimestamp() { return timestamp; }
    public boolean isSent() { return isSent; }
}